import { ref, onMounted, onUnmounted } from 'vue'

// CDN 配置
interface CDNConfig {
  baseUrl: string
  version?: string
  integrity?: string
}

interface CDNResource {
  name: string
  url: string
  type: 'css' | 'js'
  priority?: 'high' | 'low'
  preload?: boolean
  integrity?: string
}

// 常用 CDN 资源配置
export const CDN_RESOURCES: Record<string, CDNConfig> = {
  // 字体 CDN
  googleFonts: {
    baseUrl: 'https://fonts.googleapis.com',
  },
  
  // 图标 CDN
  fontAwesome: {
    baseUrl: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0',
    version: '6.4.0',
    integrity: 'sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=='
  },
  
  // UI 库 CDN
  elementPlus: {
    baseUrl: 'https://unpkg.com/element-plus@2.4.4',
    version: '2.4.4'
  },
  
  // 工具库 CDN
  lodash: {
    baseUrl: 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21',
    version: '4.17.21',
    integrity: 'sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ=='
  }
}

// 资源预加载管理器
export class ResourcePreloader {
  private loadedResources = new Set<string>()
  private loadingPromises = new Map<string, Promise<void>>()
  
  // 预加载 CSS 资源
  preloadCSS(url: string, integrity?: string): Promise<void> {
    if (this.loadedResources.has(url)) {
      return Promise.resolve()
    }
    
    if (this.loadingPromises.has(url)) {
      return this.loadingPromises.get(url)!
    }
    
    const promise = new Promise<void>((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'preload'
      link.as = 'style'
      link.href = url
      link.crossOrigin = 'anonymous'
      
      if (integrity) {
        link.integrity = integrity
      }
      
      link.onload = () => {
        // 创建实际的样式链接
        const styleLink = document.createElement('link')
        styleLink.rel = 'stylesheet'
        styleLink.href = url
        styleLink.crossOrigin = 'anonymous'
        
        if (integrity) {
          styleLink.integrity = integrity
        }
        
        document.head.appendChild(styleLink)
        this.loadedResources.add(url)
        resolve()
      }
      
      link.onerror = () => reject(new Error(`Failed to preload CSS: ${url}`))
      document.head.appendChild(link)
    })
    
    this.loadingPromises.set(url, promise)
    return promise
  }
  
  // 预加载 JavaScript 资源
  preloadJS(url: string, integrity?: string): Promise<void> {
    if (this.loadedResources.has(url)) {
      return Promise.resolve()
    }
    
    if (this.loadingPromises.has(url)) {
      return this.loadingPromises.get(url)!
    }
    
    const promise = new Promise<void>((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'preload'
      link.as = 'script'
      link.href = url
      link.crossOrigin = 'anonymous'
      
      if (integrity) {
        link.integrity = integrity
      }
      
      link.onload = () => {
        // 创建实际的脚本标签
        const script = document.createElement('script')
        script.src = url
        script.crossOrigin = 'anonymous'
        script.defer = true
        
        if (integrity) {
          script.integrity = integrity
        }
        
        script.onload = () => {
          this.loadedResources.add(url)
          resolve()
        }
        
        script.onerror = () => reject(new Error(`Failed to load JS: ${url}`))
        document.head.appendChild(script)
      }
      
      link.onerror = () => reject(new Error(`Failed to preload JS: ${url}`))
      document.head.appendChild(link)
    })
    
    this.loadingPromises.set(url, promise)
    return promise
  }
  
  // 批量预加载资源
  async preloadResources(resources: CDNResource[]): Promise<void> {
    const promises = resources.map(resource => {
      if (resource.type === 'css') {
        return this.preloadCSS(resource.url, resource.integrity)
      } else {
        return this.preloadJS(resource.url, resource.integrity)
      }
    })
    
    await Promise.allSettled(promises)
  }
  
  // 检查资源是否已加载
  isLoaded(url: string): boolean {
    return this.loadedResources.has(url)
  }
  
  // 清理资源
  cleanup(): void {
    this.loadedResources.clear()
    this.loadingPromises.clear()
  }
}

// 全局资源预加载器实例
export const resourcePreloader = new ResourcePreloader()

// 字体预加载 Hook
export function useFontPreload() {
  const loadGoogleFonts = async (families: string[]) => {
    const fontUrl = `${CDN_RESOURCES.googleFonts.baseUrl}/css2?${families.map(family => `family=${encodeURIComponent(family)}`).join('&')}&display=swap`
    
    try {
      await resourcePreloader.preloadCSS(fontUrl)
      console.log('Google Fonts loaded successfully')
    } catch (error) {
      console.error('Failed to load Google Fonts:', error)
    }
  }
  
  const preloadFontAwesome = async () => {
    const config = CDN_RESOURCES.fontAwesome
    const cssUrl = `${config.baseUrl}/css/all.min.css`
    
    try {
      await resourcePreloader.preloadCSS(cssUrl, config.integrity)
      console.log('Font Awesome loaded successfully')
    } catch (error) {
      console.error('Failed to load Font Awesome:', error)
    }
  }
  
  return {
    loadGoogleFonts,
    preloadFontAwesome
  }
}

// 图片 CDN 优化 Hook
export function useImageCDN() {
  // 图片质量优化
  const optimizeImageUrl = (url: string, options: {
    width?: number
    height?: number
    quality?: number
    format?: 'webp' | 'avif' | 'auto'
  } = {}) => {
    const { width, height, quality = 80, format = 'auto' } = options
    
    // Cloudinary CDN 优化
    if (url.includes('cloudinary.com')) {
      let transformations = [`q_${quality}`]
      
      if (width) transformations.push(`w_${width}`)
      if (height) transformations.push(`h_${height}`)
      if (format !== 'auto') transformations.push(`f_${format}`)
      
      return url.replace('/upload/', `/upload/${transformations.join(',')}/`)
    }
    
    // ImageKit CDN 优化
    if (url.includes('imagekit.io')) {
      const params = new URLSearchParams()
      params.set('tr', `q-${quality}`)
      
      if (width) params.set('w', width.toString())
      if (height) params.set('h', height.toString())
      if (format !== 'auto') params.set('f', format)
      
      return `${url}?${params.toString()}`
    }
    
    return url
  }
  
  // 响应式图片 srcset 生成
  const generateSrcSet = (baseUrl: string, sizes: number[] = [320, 640, 1024, 1920]) => {
    return sizes.map(size => {
      const optimizedUrl = optimizeImageUrl(baseUrl, { width: size })
      return `${optimizedUrl} ${size}w`
    }).join(', ')
  }
  
  return {
    optimizeImageUrl,
    generateSrcSet
  }
}

// 资源压缩和缓存 Hook
export function useResourceOptimization() {
  const cacheVersion = ref('1.0.0')
  
  // 检查浏览器支持的压缩格式
  const getSupportedFormats = () => {
    const canvas = document.createElement('canvas')
    canvas.width = 1
    canvas.height = 1
    
    return {
      webp: canvas.toDataURL('image/webp').indexOf('data:image/webp') === 0,
      avif: canvas.toDataURL('image/avif').indexOf('data:image/avif') === 0
    }
  }
  
  // 资源缓存策略
  const cacheResource = (url: string, data: any, ttl: number = 3600000) => {
    const cacheKey = `resource_${btoa(url)}`
    const cacheData = {
      data,
      timestamp: Date.now(),
      ttl,
      version: cacheVersion.value
    }
    
    try {
      localStorage.setItem(cacheKey, JSON.stringify(cacheData))
    } catch (error) {
      console.warn('Failed to cache resource:', error)
    }
  }
  
  // 获取缓存资源
  const getCachedResource = (url: string) => {
    const cacheKey = `resource_${btoa(url)}`
    
    try {
      const cached = localStorage.getItem(cacheKey)
      if (!cached) return null
      
      const cacheData = JSON.parse(cached)
      const now = Date.now()
      
      // 检查版本和过期时间
      if (cacheData.version !== cacheVersion.value || 
          now - cacheData.timestamp > cacheData.ttl) {
        localStorage.removeItem(cacheKey)
        return null
      }
      
      return cacheData.data
    } catch (error) {
      console.warn('Failed to get cached resource:', error)
      return null
    }
  }
  
  // 清理过期缓存
  const cleanupCache = () => {
    const keys = Object.keys(localStorage)
    const now = Date.now()
    
    keys.forEach(key => {
      if (key.startsWith('resource_')) {
        try {
          const cached = localStorage.getItem(key)
          if (cached) {
            const cacheData = JSON.parse(cached)
            if (cacheData.version !== cacheVersion.value || 
                now - cacheData.timestamp > cacheData.ttl) {
              localStorage.removeItem(key)
            }
          }
        } catch (error) {
          localStorage.removeItem(key)
        }
      }
    })
  }
  
  return {
    cacheVersion,
    getSupportedFormats,
    cacheResource,
    getCachedResource,
    cleanupCache
  }
}

// CDN性能监控 Hook
export function useCDNPerformanceMonitor() {
  const metrics = ref({
    resourceLoadTime: 0,
    totalResources: 0,
    failedResources: 0,
    cacheHitRate: 0
  })
  
  const startTime = ref(0)
  const resourceTimings = ref<PerformanceResourceTiming[]>([])
  
  const startMonitoring = () => {
    startTime.value = performance.now()
    
    // 监听资源加载
    const observer = new PerformanceObserver((list) => {
      const entries = list.getEntries() as PerformanceResourceTiming[]
      resourceTimings.value.push(...entries)
      updateMetrics()
    })
    
    observer.observe({ entryTypes: ['resource'] })
    
    return () => observer.disconnect()
  }
  
  const updateMetrics = () => {
    const timings = resourceTimings.value
    metrics.value.totalResources = timings.length
    metrics.value.resourceLoadTime = timings.reduce((sum, timing) => 
      sum + (timing.responseEnd - timing.startTime), 0
    )
    metrics.value.failedResources = timings.filter(timing => 
      timing.transferSize === 0 && timing.decodedBodySize === 0
    ).length
  }
  
  const getResourceMetrics = () => {
    return {
      ...metrics.value,
      averageLoadTime: metrics.value.totalResources > 0 
        ? metrics.value.resourceLoadTime / metrics.value.totalResources 
        : 0
    }
  }
  
  return {
    metrics,
    startMonitoring,
    getResourceMetrics
  }
}

// 自动资源优化 Hook
export function useAutoOptimization() {
  const { getSupportedFormats, cleanupCache } = useResourceOptimization()
  
  const initializeOptimizations = async () => {
    // 清理过期缓存
    cleanupCache()
    
    // 在组件实例内调用 useFontPreload
    const { loadGoogleFonts, preloadFontAwesome } = useFontPreload()
    
    // 预加载关键字体
    await Promise.allSettled([
      loadGoogleFonts(['Inter:wght@400;500;600;700']),
      preloadFontAwesome()
    ])
    
    // 检测并应用最佳图片格式
    const formats = getSupportedFormats()
    console.log('Supported image formats:', formats)
    
    // 预连接到 CDN
    const preconnectUrls = [
      'https://fonts.googleapis.com',
      'https://fonts.gstatic.com',
      'https://cdnjs.cloudflare.com'
    ]
    
    preconnectUrls.forEach(url => {
      const link = document.createElement('link')
      link.rel = 'preconnect'
      link.href = url
      link.crossOrigin = 'anonymous'
      document.head.appendChild(link)
    })
  }
  
  return {
    initializeOptimizations
  }
}